import json
import os
import subprocess
import time
import uuid

from PIL import ImageFile
from dotenv import load_dotenv

import agent_config
from AgentTool.doubao_itv import viduGenerator_doubao
from AgentTool.google_veo_itv import ViduGenerator_google_veo
from AgentTool.keling_itv import videoGenerator_kling
from AgentTool.lumalabs import LumaVideoGenerator
from AgentTool.minimax_itv import MiniMaxVideoGenerator
from AgentTool.openai_itv import generator_openai
from AgentTool.pixverse_itv import ViduGenerator_pixverse
from AgentTool.vidu_itv import viduGenerator_Vid
from AgentTool.wanxiang_itv import wanXiangGenerator_Vid
from add_watermark_service import local_check_txt_nsfw
from agent_config import calculate_super_resolution
from utils import sr_s3, sr_utils, sqs_video, status_codes, video_utils

from openai import OpenAI

from utils.sr_utils import video_compress_image_size_path, download_image_upload_s3
from utils.video_utils import process_video_with_watermark_service

# 配置与初始化
load_dotenv(verbose=True, override=True)
ImageFile.LOAD_TRUNCATED_IMAGES = True  # 处理截断图片

# 环境变量与客户端初始化
app_env = os.getenv('APP_ENV', 'prod')

StatusCodes = status_codes.StatusCodes

# 队列初始化
try:
    if app_env == 'dev':
        TASK_QUEUE = sqs_video.videoSQS.get_queue_by_name(QueueName='AIHubVideoTasks_Test')
        sr_s3.set_logging("连接到开发环境队列: AIHubVideoTasks_Test")
    else:
        TASK_QUEUE_NAME = agent_config.TASK_QUEUE_AIGCVIDEO_NAME
        TASK_QUEUE = sqs_video.videoSQS.get_queue_by_name(QueueName=TASK_QUEUE_NAME)
        sr_s3.set_logging(f"连接到生产环境队列: {TASK_QUEUE_NAME}")
    
    print(TASK_QUEUE)
    sr_s3.set_logging("SQS队列连接成功")
except Exception as e:
    sr_s3.set_logging(f"SQS队列连接失败: {e}")
    raise


def get_resolution(num):
    data = {
        0: (300, 6000),
        20: (300, 6000),
        21: (300, 6000),
        22: (300, 4000),
        23: (300, 6000),
        24: (300, 4000),
        25: (300, 6000),
        26: (300, 6000),
        27: (360, 2000),
    }
    # 使用 get 方法，如果 num 不在字典中，则返回默认值 (300, 4000)
    return data.get(num, (300, 4000))


def send_result_to_queue(queue_name, body, status, msg, results=None, code=None, start_time=None, ai_star_time=None, ai_end_time=None, local_time=None, local_video=None, code_json=None):
    """发送结果到指定队列"""
    if local_video is None:
        local_video = {
            "width": 0,
            "height": 0,
            "fps": 0,
            "tokens": 0,
        }
    token = local_video.get("tokens", 0)
    width = local_video.get("width", 0)
    height = local_video.get("height", 0)
    fps = local_video.get("fps", 0)
    try:
        results = results or {}
        msg_body = {
            'QueueResult': queue_name,
            'status': status,
            'taskId': body.get('taskId'),
            'taskType': body.get('taskType'),
            'appId': body.get('appId'),
            'machineId': 1,
            'width': width,
            'height': height,
            'tokens': token,
            'fps': fps,
            'results': results,
            'msgFetchEndTime': start_time,
            'start_time': start_time,
            'imageAIStartTime': ai_star_time,
            'imageAIEndTime': ai_end_time,
            'end_time': sr_utils.getTimes(local_time),
            'msg': msg,
            'code': code,
            'code_json': code_json
        }
        print(msg_body)
        queue = sqs_video.videoSQS.get_queue_by_name(QueueName=queue_name)
        queue.send_message(MessageBody=json.dumps(msg_body))
        sr_s3.set_logging(f"已发送结果到队列 {queue_name}: {status}")
        print(f"已发送结果到队列 {queue_name}: {status}")
    except Exception as e:
        sr_s3.set_logging(f"发送队列消息失败: {str(e)}")
        print(f"发送队列消息失败: {str(e)}")


def send_vsr_task_queue(queue_name, body, urlkey, resolution, Model_scale=2, local_video=None, code_json=None):
    """超分发送结果到指定队列"""
    if app_env == 'dev':
        Task_queue_name = "AILocalVideoGenerate"
        # Task_queue_name = "AITestVideoGenerate"
        queue_name = "video_media_thumbmark_Test"
    else:
        Task_queue_name = "AIVideoGenerate"
        queue_name = agent_config.TASK_QUEUE_THUMBMART_NAME

    if local_video is None:
        local_video = {
            "width": 0,
            "height": 0,
            "fps": 0,
            "tokens": "0",
        }
    tokens = local_video.get("tokens", 0)
    target_height = local_video.get("target_height", 0)
    target_width = local_video.get("target_width", 0)
    msg_body = {
        "taskId": body.get('taskId'),
        "file": urlkey,
        "scale": Model_scale,
        "width": target_width,
        "height": target_height,
        "appId": body.get('appId'),
        "taskType": body.get('taskType'),
        "QueueResult": queue_name,
        "storageService": body.get('storageService'),
        "isLogin": body.get('isLogin'),
        "bucketName": body.get('bucketName'),
        "storedPrefix": body.get('storedPrefix'),
        "start_time": 0,
        "modelType": 1,
        "stop_time": -1,
        "moduleType": 1,
        "code": 200,
        "progress": body.get('progress'),
        "results_attach": {
            "create_time": int(time.time()),
            "origin_image": urlkey,
            "resolution": resolution,
            "storageService": body.get('storageService'),
            "bucketName": body.get('bucketName'),
            "storedPrefix": body.get('storedPrefix'),
            "tokens": tokens,
            "code_json": code_json
        }
    }
    print("超分任务参数：", msg_body)
    queue = sqs_video.videoSQS.get_queue_by_name(QueueName=Task_queue_name)
    queue.send_message(MessageBody=json.dumps(msg_body))
    sr_s3.set_logging(f"已发任务到队列 {Task_queue_name}")
    print(f"已发任务到队列 {Task_queue_name}")
    # except Exception as e:
    #     print(f"发送队列消息失败: {str(e)}")


def process_video(body, moduleType, local_time):
    """
            # ########################################################
            # doubao 20 ,21 klingai,22 pixVerse ,23 google veo 24 海螺ai
            # result 返回结构：
            # "status": 1,                      # 1成功，0失败
            # "width": 3840,                    # 分辨率
            # "height": 2160,                   # 分辨率
            # "model_mode: 'pro', 'std', 'lite' # 相同的模型ID，模型类型区分，默认 std 标准，不区分概念
            # "url": "/xxx/xxx.mp4",        # 视频存储桶路径
            # ########################################################
        """
    print("moduleType", moduleType)
    if moduleType == 20:
        # 处理任务
        result = viduGenerator_doubao(body, local_time)
        print("doubao")
    elif moduleType == 21:
        print("kling")
        video_generator = videoGenerator_kling()
        result = video_generator.process_video_task(body)
        print(result)
    elif moduleType == 22:
        print("pixVerse")
        result = ViduGenerator_pixverse(body)

    elif moduleType == 23:
        print("google veo")
        result = ViduGenerator_google_veo(body)

    elif moduleType == 24:
        print("vidu")
        video_generator = viduGenerator_Vid()
        result = video_generator.process_video_task_vidu(body)

    elif moduleType == 25:
        print("minimax")
        generator = MiniMaxVideoGenerator()

    elif moduleType == 26:
        print("Luma")
        generator = LumaVideoGenerator()
        result = generator.process_video_task(body)

    elif moduleType == 27:
        print("wanXiang")
        generator = wanXiangGenerator_Vid()
        result = generator.process_video_task_wx(body)

    elif moduleType == 28:
        print("sora-2")
        result = generator_openai(body)

    return result


# --------------------------
# 主循环逻辑
# --------------------------
def main():
    sr_s3.set_logging('视频生成服务启动')
    local_time = sr_utils.time_difference()
    print(local_time)
    sr_s3.set_logging(f'服务器时间差: {local_time}')
    sr_s3.set_logging("服务启动")
    while True:
        if os.path.exists('./stop'):
            break
        try:
            # 从队列获取消息
            sr_s3.set_logging("准备从队列获取消息")
            try:
                messages = TASK_QUEUE.receive_messages(MaxNumberOfMessages=1, WaitTimeSeconds=20)
                sr_s3.set_logging(f"接收到 {len(messages)} 条消息")
            except Exception as e:
                sr_s3.set_logging(f"从队列获取消息时发生错误: {str(e)}")
                sr_s3.set_logging("等待一段时间后重试...")
                time.sleep(5)  # 等待5秒后重试
                continue
            print(len(messages))
            if len(messages) == 0:
                sr_s3.set_logging("未接收到消息，继续等待")
                time.sleep(1)
                continue

            body = json.loads(messages[0].body)
            sr_s3.set_logging(f"收到任务消息: {body}")
            print(f"body: {body}")
            messages[0].delete()
            sr_s3.set_logging("已删除队列消息")

            task_id = body.get('taskId', 0)
            if task_id == 0:
                sr_s3.set_logging(f'taskId is null: {task_id}')
                sr_s3.set_logging(f'Error taskId is null: {task_id}')
                continue
            print(f"收到任务: {task_id}")
            sr_s3.set_logging(f'收到任务 Msg: {task_id}')
            start_time = sr_utils.getTimes(local_time)
            err_message = "success"  # 判断GPT检测是否成功
            code_json = [
                {
                    "code1": 200,
                    "message": {}
                },
                {
                    "code2": 200,
                    "message": {}
                },
                {
                    "code3": 200,
                    "message": {}
                },
                {
                    "code4": 200,
                    "message": {}
                },
            ]  # 储存检测为nsfw但是放行的数据
            try:
                # 开始处理任务【加进度 5%】
                # code..

                # 清理
                # sr_utils.delFiles('./upload/')
                # sr_utils.delFiles('./results/')
                # sr_utils.delFiles('./download/')

                """统一处理视频生成任务（入口函数）"""
                task_id = body.get('taskId', 'unknown')
                queue_result = body.get('QueueResult')
                storage_service = body.get('storageService', 's3')
                bucket_name = body.get('bucketName')
                s3_storage = body.get('storedPrefix')
                first_image = body.get('first_image', None)
                last_image = body.get('last_image', None)

                duration = body.get('duration', 5)
                # 模型类型
                modelType = body.get("modelType", 0)
                # 模块类型
                moduleType = body.get("moduleType", 0)
                # 模块类型
                moduleName = body.get("moduleName", None)
                # 必传参数校验
                required_params = ['prompt']
                prompt_check = True
                nsfw_scores = body.get("nsfw_scores", None)
                prompt = body.get('prompt')
                print("prompt:", prompt)

                # 开始风控检测【加进度 10%】
                # code..

                # 更直观的实现方式#######################
                need_nsfw_check = False

                # 判断是否需要进行 NSFW 检测
                # if body.get('template') and moduleType == 24:
                if body.get('template'):
                    # 对于 vidu 模板模式，默认不需要检测
                    need_nsfw_check = False
                    # 但 relax_cut 模板需要检测
                    if body.get('template') == "relax_cut":
                        need_nsfw_check = True
                else:
                    for param in required_params:
                        if not body.get(param):
                            err_msg = f"缺参数: {param}"
                            prompt_check = False
                            break

                    if not prompt_check:
                        send_result_to_queue(queue_result, body, 0, err_msg, code=StatusCodes.PARAMETER_ERROR, start_time=start_time, local_time=local_time)
                        continue
                    # 非模板模式需要检测
                    need_nsfw_check = True

                # 执行 NSFW 检测
                if need_nsfw_check:
                    clientOpenAI = OpenAI()
                    local_check_prompt_nsfw, code, err_message = sr_utils.content_moderations(clientOpenAI, 3, "", prompt)
                    if code == 5:
                        success = video_utils.check_content_review(err_message, nsfw_scores)
                        if success:
                            code_json[0] = {
                                "code1": StatusCodes.INPUT_TEXT_INVALID_MODEL_THRESHOLD,
                                "message": err_message
                            }
                            err_msg = "prompt txt 不合规 打分: {} 内容: {}".format(err_message, prompt)
                            send_result_to_queue(queue_result, body, 7, err_msg, code=StatusCodes.INPUT_TEXT_INVALID_GPT, start_time=start_time, local_time=local_time, code_json=code_json)
                            continue
                        else:
                            code_json[0] = {
                                "code1": StatusCodes.INPUT_TEXT_INVALID_MODEL_THRESHOLD,
                                "message": err_message
                            }

                ####################################################################
                # code first_image，last_image 图片转换 支持 格式
                # 1. jpg, jpeg, png, webp, bmp
                # 替换 body 对象里 first_image，last_image
                # body
                ####################################################################

                resolution_value = get_resolution(int(moduleType))
                if first_image:
                    success, first_image,locapath, err_str = download_image_upload_s3(first_image, storage_service, bucket_name, s3_storage, resolution_value)
                    body['locaPath'] = locapath
                    if not success:
                        err_msg = "图片处理失败" + err_str
                        send_result_to_queue(queue_result, body, 0, err_msg, code=StatusCodes.IMAGE_PROCESS_ERROR, start_time=start_time, local_time=local_time)
                        continue
                    body['first_locaPath'] = locapath
                    body['first_image'] = first_image
                    clientOpenAI = OpenAI()
                    fimage = sr_s3.get_url(first_image, serviceName=storage_service, bucketName=bucket_name)
                    need_nsfw_check, code, err_message = sr_utils.content_moderations(clientOpenAI, 1, fimage)
                    if need_nsfw_check:
                        success = video_utils.check_content_review(err_message, nsfw_scores)
                        if success:
                            code_json[1] = {
                                "code2": StatusCodes.INPUT_IMAGE_INVALID_GPT_THRESHOLD,
                                "message": err_message
                            }
                            err_msg = "图片不合规 打分: {}".format(err_message)
                            send_result_to_queue(queue_result, body, 7, err_msg, code=StatusCodes.INPUT_IMAGE_INVALID_GPT, start_time=start_time, local_time=local_time, code_json=code_json)
                            continue
                        else:
                            code_json[1] = {
                                "code2": StatusCodes.INPUT_IMAGE_INVALID_GPT_THRESHOLD,
                                "message": err_message
                            }
                if last_image:
                    success, last_image,locapath, err_str = download_image_upload_s3(last_image, storage_service, bucket_name, s3_storage, resolution_value)
                    if not success:
                        err_msg = "图片处理失败" + err_str
                        send_result_to_queue(queue_result, body, 0, err_msg, code=StatusCodes.IMAGE_PROCESS_ERROR, start_time=start_time, local_time=local_time)
                        continue
                    body['last_locaPath'] = locapath
                    body['last_image'] = last_image
                    clientOpenAI = OpenAI()
                    fimage = sr_s3.get_url(last_image, serviceName=storage_service, bucketName=bucket_name)
                    need_nsfw_check, code, err_message = sr_utils.content_moderations(clientOpenAI, 1, fimage)
                    if need_nsfw_check:
                        success = video_utils.check_content_review(err_message, nsfw_scores)
                        if success:
                            code_json[2] = {
                                "code3": StatusCodes.INPUT_IMAGE_INVALID_GPT_THRESHOLD,
                                "message": err_message
                            }
                            err_msg = "图片不合规 打分: {}".format(err_message)
                            send_result_to_queue(queue_result, body, 7, err_msg, code=StatusCodes.INPUT_IMAGE_INVALID_GPT, start_time=start_time, local_time=local_time, code_json=code_json)
                            continue
                        else:
                            code_json[2] = {
                                "code3": StatusCodes.INPUT_IMAGE_INVALID_GPT_THRESHOLD,
                                "message": err_message
                            }

                # 开始翻译检测【加进度 15%】
                # code..

                # 翻译#######################
                # 获取翻译开关参数
                p_t_b = body.get('p_t_b', 0)  # prompt翻译开关，默认关闭(0)
                n_t_b = body.get('n_t_b', 0)  # negative_prompt翻译开关，默认关闭(0)

                # 根据开关翻译提示词
                if p_t_b == 1:
                    prompt_lang = sr_utils.translate_text(prompt)
                    # 修改 body 里的 prompt 为 translated_prompt
                    if isinstance(prompt_lang, dict) and 'translated_prompt' in prompt_lang:
                        body['prompt'] = prompt_lang['translated_prompt']
                    elif isinstance(prompt_lang, str):
                        body['prompt'] = prompt_lang
                    print("翻译后 prompt:", body['prompt'])

                # 如果有反向提示词且开关打开，也进行翻译
                negative_prompt = body.get('negative_prompt', '')
                if n_t_b == 1 and negative_prompt:
                    negative_prompt_lang = sr_utils.translate_text(negative_prompt)
                    # 修改 body 里的 negative_prompt 为 translated_negative_prompt
                    if isinstance(negative_prompt_lang, dict) and 'translated_prompt' in negative_prompt_lang:
                        body['negative_prompt'] = negative_prompt_lang['translated_prompt']
                    elif isinstance(negative_prompt_lang, str):
                        body['negative_prompt'] = negative_prompt_lang
                    print("翻译后 negative_prompt:", body['negative_prompt'])
                # 翻译 结束结束##############

                resolution = body.get('resolution', "480p")
                mResolution = body.get('mResolution', "720p")
                ratio = body.get('ratio', None)

                # 开始第三方AI【加进度 20%】
                # code..
                print("开始第三方AI")
                AITimeS = sr_utils.getTimes(local_time)
                """ # ################## 第三方对接 #########################"""
                result = process_video(body, moduleType, local_time)
                """ # ###################################################"""
                """ # 处理结果 """
                AITimeE = sr_utils.getTimes(local_time)
                print("AI处理时间:", f" {(AITimeE - AITimeS) / 1000} ms")
                sr_s3.set_logging(f"AI处理时间: {(AITimeE - AITimeS) / 1000} ms")

                # result = {"status": 1, "width": 1280, "height": 720, "fps": 30.0, "url": "video/image_to_video/2025-10-16/ffb20422a5cb45cfb8675978c7510fa4/video_task_video_68f0d8c7255c819092e3878a9b28159a0d954788b4437783.mp4", "local_path": "./download/videos/video_task_video_68f0d8c7255c819092e3878a9b28159a0d954788b4437783.mp4", "msg": "success", "code": ""}

                # 开始三方AI结束时间长【加进度 70%】
                # code..
                print("处理结果result: ", result)
                # 优化后的模板/模型模式判断逻辑
                template_id = body.get('template', None)

                # 判断是否为模板模式
                # 条件：有template参数 且 无moduleName参数
                is_template_mode = bool(template_id) and not bool(moduleName)

                if is_template_mode:
                    # 模板模式处理
                    print("当前为模板模式")
                    # 根据moduleType设置特定参数
                    if moduleType == 24:
                        moduleName = "viduq1"
                        resolution = mResolution.lower()
                else:
                    # 模型模式处理
                    print("当前为模型模式")
                    # 模型模式必须提供moduleName
                    if not moduleName:
                        raise Exception("模型模式下必须提供moduleName参数")

                target_quality = resolution
                if moduleName:
                    moduleName = moduleName.lower()

                result_status = result.get('status', 0)
                result_code = result.get('code', None)
                print("处理结果result: ", result)
                if result_status == 1:
                    print(f"任务{task_id}处理成功，url:", result.get('url'))
                    # 用户选择比例
                    aspect_ratio = ratio
                    # 第三方结果高宽分辨率
                    custom_width = result.get('width')
                    custom_height = result.get('height')
                    model_mode = result.get('model_mode', 'std').lower()
                    local_path = result.get("local_path")
                    tokens = result.get("tokens")
                    url = result.get("url")

                    if custom_width is None or custom_height is None:
                        raise Exception("分辨率获取失败", task_id)

                    if not is_template_mode:
                        # 根据第三方结果获取放大倍数和目标分辨率，并计算目标分辨率，决定是否需要超分；
                        try:
                            print(moduleName, target_quality, aspect_ratio, custom_width, custom_height, moduleType, duration, model_mode)
                            result_sr = calculate_super_resolution(moduleName, target_quality, aspect_ratio, duration=duration, mode=model_mode, custom_width=int(custom_width), custom_height=int(custom_height), module_type=moduleType)
                            print("获取模型配置超分信息成功", result_sr)
                        except Exception as e:
                            err_msg = "获取模型配置超分信息失败: {}".format(e)
                            send_result_to_queue(queue_result, body, 2, err_msg, code=StatusCodes.PARAMETER_ERROR, start_time=start_time, local_time=local_time)
                            continue

                        scale = result_sr['multiplier']
                        target_width, target_height = result_sr['target_resolution']
                    else:
                        # 是模板模式 template 结果获取放大倍数和目标分辨率，决定是否需要超分；
                        result_sr = agent_config.calculate_template_ratio_resolution(module_type=moduleType, duration=duration, target_quality=target_quality, custom_width=int(custom_width), custom_height=int(custom_height))
                        print("获取【模板】配置超分信息成功", result_sr)
                        scale = result_sr['multiplier']
                        target_width, target_height = result_sr['target_resolution']

                    # 分支路线
                    # 开始结果处理，水印【加进度 90%】【不超分】
                    # code..分支路线
                    # 开始超分处理【加进度 75%】【超分】（预计1分钟内）
                    # code..

                    if scale == 1:
                        print("\033[32m==>无需超分辨率\033[0m", scale)
                        try:
                            print("调用进程 命令 添加水印")
                            watermark_result = process_video_with_watermark_service(local_path, task_id, resolution, storage_service=storage_service, bucket_name=bucket_name, s3_prefixes_path=s3_storage, extract_thumbnail=True, extract_watermark=True, nsfw_check=True)
                            print("调用进程 命令 添加水印", watermark_result)
                            if watermark_result["status"] == 1:
                                wm_results = {"origin_image": url, "key": url, "watermark": watermark_result["watermark"], "thumbnail": watermark_result["thumbnail"]}
                            else:
                                # 水印处理失败，返回原始视频
                                wm_results = {"origin_image": url, "key": url, "watermark": url, "thumbnail": "", "code": watermark_result.get('code', '5013')}
                            err_json = watermark_result.get('err_json', "")
                            if len(err_json) > 0:
                                watermark_success = video_utils.check_content_review(err_json, nsfw_scores)
                                if watermark_success:
                                    code_json[3] = {
                                        "code4": StatusCodes.OUTPUT_VIDEO_INVALID_GPT_THRESHOLD,
                                        "message": err_json
                                    }
                                    err_msg = "模型输出视频检测不合规 打分: {}".format(err_json)
                                    send_result_to_queue(queue_result, body, 7, err_msg, code=StatusCodes.OUTPUT_VIDEO_INVALID_GPT, results=wm_results, start_time=start_time, ai_star_time=AITimeS, ai_end_time=AITimeE, local_time=local_time, local_video=result, code_json=code_json)
                                    continue
                                else:
                                    code_json[3] = {
                                        "code4": StatusCodes.OUTPUT_VIDEO_INVALID_GPT_THRESHOLD,
                                        "message": err_json
                                    }

                        except Exception as e:
                            wm_results = {"origin_image": url, "key": url, "watermark": url, "thumbnail": "", "code": watermark_result.get('code', '5013')}
                            print(f"视频处理失败: {watermark_result.get('msg')}")

                        result_code = watermark_result.get('code', '5013')
                        send_result_to_queue(queue_result, body, 1, err_message, code=result_code, results=wm_results, start_time=start_time, ai_star_time=AITimeS, ai_end_time=AITimeE, local_time=local_time, local_video=result, code_json=code_json)
                    else:
                        print("==>开始超分处理中:", scale)
                        sr_s3.set_logging(f"任务{task_id}开始超分处理: {scale}")
                        try:
                            watermark_result = process_video_with_watermark_service(local_path, task_id, "0", storage_service=storage_service, bucket_name=bucket_name, s3_prefixes_path=s3_storage, extract_thumbnail=False, extract_watermark=False, nsfw_check=True)
                        except Exception as e:
                            watermark_result["status"] = 1
                        get_code_json = watermark_result.get("err_json", "")

                        if len(get_code_json) > 0:  # 判断检测是否违规
                            watermark_success = video_utils.check_content_review(get_code_json, nsfw_scores)
                            if watermark_success:
                                code_json[3] = {
                                    "code4": StatusCodes.OUTPUT_VIDEO_INVALID_GPT_THRESHOLD,
                                    "message": get_code_json
                                }
                                err_msg = "模型输出视频检测不合规 打分: {}".format(get_code_json)
                                wm_results = {"origin_image": url, "key": url, "watermark": url, "thumbnail": "", "code": watermark_result.get('code', '5013')}
                                send_result_to_queue(queue_result, body, 7, err_msg, results=wm_results, code=StatusCodes.OUTPUT_VIDEO_INVALID_GPT, start_time=start_time, local_time=local_time, code_json=code_json)
                                continue
                            code_json[3] = {
                                "code4": StatusCodes.OUTPUT_VIDEO_INVALID_GPT_THRESHOLD,
                                "message": get_code_json
                            }
                        send_vsr_task_queue(queue_result, body, url, resolution, Model_scale=scale, local_video={"target_width": target_width, "target_height": target_height, "tokens": tokens}, code_json=code_json)
                    print("\033[32m==>视频处理完毕\033[0m", queue_result)
                else:
                    err = result.get('msg')
                    queue_result = body.get('QueueResult', 'None')
                    send_result_to_queue(queue_result, body, result_status, err, code=result_code, start_time=start_time, local_time=local_time, code_json=code_json)
                    print(f"任务{task_id}处理失败: {err}")
                    sr_s3.set_logging(f"任务{task_id}处理失败: {err}")
                # 无论成功失败，删除消息避免重复处理
                print(f"已删除队列消息: {task_id}")
                endT = sr_utils.getTimes(local_time)
                sr_s3.set_logging(f"已删除队列消息: {task_id}")
                sr_s3.set_logging(f"总时间: {task_id} {(endT - start_time) / 1000} ms")
            except Exception as e:
                err = str(e)
                sr_s3.set_logging(f'任务 Msg: {task_id} 异常:{err}')
                queue_result = body.get('QueueResult', 'None')
                result_code = StatusCodes.TASK_FAILED
                send_result_to_queue(queue_result, body, 0, err, code=result_code, start_time=start_time, local_time=local_time, code_json=code_json)
                sr_s3.set_logging(f"任务处理异常: {str(e)}")
                print(f"任务处理异常: {str(e)}")
                time.sleep(1)  # 异常后暂停5秒再重试
        except Exception as e:
            sr_s3.set_logging(f"主循环异常: {str(e)}")
            print(f"主循环异常: {str(e)}")
            time.sleep(1)  # 异常后暂停1秒再重试


if __name__ == "__main__":
    main()